using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Support.V4.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using mb.Droid;
using Shared;
using Xamarin.Forms.Platform.Android;

namespace libmp
{
    class OfflineCacheView : BaseMixList<DataStore.VideoItem>
    {
        MyFragment myFragment;
        LinearLayout bottomBar;
        SelectOperatePage selectOperatePage;

        HashSet<int> selectedVideo = new HashSet<int>();
        List < (int vid, long total, long now) > offlineItemInfoList;

        public MyFragment CreateFragment()
        {
            myFragment = new MyFragment()
            {
                MyOnCreateView = (f, container) =>
                    {
                        return CreateView();
                    },
                    MyOnReEnter = f =>
                    {
                        ReloadData();
                    }
            };
            return myFragment;
        }

        public OfflineCacheView()
        {
            ReloadData();
        }

        void ReloadData()
        {
            try
            {
                offlineItemInfoList = GlobalImpl.VideoServer.GetOfflineItemInfoList();

                dataSource = offlineItemInfoList.Select(item =>
                {
                    logger.Log("item", item);
                    return DataStore.store.GetVideoItemById(item.vid);
                }).ToList();
            }

            catch (Exception)
            {
                dataSource = DataStore.store.GetAllVideo();
                dataSource = new List<DataStore.VideoItem>();
            }

            if (adapter != null)
            {
                Reload();
            }
        }

        public View CreateView()
        {
            LinearLayout layout = new LinearLayout(activity);
            layout.Orientation = Orientation.Vertical;
            layout.SetBackgroundColor(Util.MainBKColor);
            layout.FillParent();
            layout.AddView(CreateTitleBar());
            layout.AddView(new LinearLayout(activity) { LayoutParameters = new ViewGroup.LayoutParams(-1, 10) });

            SetupAdaptor();
            adapter.HasStableIds = true;
            adapter.MyGetItemId = (p) =>
            {
                return dataSource[p].vid;
            };

            Setup();
            Reload();

            layout.AddView(GetListView());
            layout.AddView(CreateBottomBar());

            return layout;
        }

        bool _selectMode;
        bool SelectMode
        {
            get { return _selectMode; }
            set
            {
                _selectMode = value;
                if (value)
                {
                    bottomBar.Visibility = ViewStates.Visible;
                }
                else
                {
                    bottomBar.Visibility = ViewStates.Gone;
                    selectedVideo.Clear();
                }

                UpdateAll();
            }
        }

        View CreateTitleBar()
        {
            return Common.CreateTitleBar(new Common.TitleBarOption()
            {
                Title = "离线视频",
                    MenuItems = new []
                    {
                        ("全部删除", new Action(() => { DeleteAll(); }))
                    }.ToList(),
            });
        }

        View CreateBottomBar()
        {
            bottomBar = new LinearLayout(activity)
            {
                Id = View.GenerateViewId(),
                Orientation = Orientation.Horizontal,
                Visibility = ViewStates.Gone,
                LayoutParameters = new LinearLayout.LayoutParams(-1, Util.dpToPx(40))
            };

            selectOperatePage = new SelectOperatePage(
                onCancel: () =>
                {
                    SelectMode = false;
                },
                onConfirm: () =>
                {
                    DeleteSelected();
                },
                onSelectAll: (b) =>
                {
                    // logger.Log("selectall", b);
                    selectedVideo.Clear();
                    if (b) dataSource.ForEach(v => selectedVideo.Add(v.vid));

                    UpdateAll();
                    selectOperatePage.Count = selectedVideo.Count;
                }
            );
            selectOperatePage.SetParent(myFragment, bottomBar);

            return bottomBar;
        }

        protected override View CreateCell(Dictionary<string, object> viewData)
        {
            int pad = 20;
            var squareLayout = new MySquareLayout(activity, 1.0f);
            squareLayout.Id = View.GenerateViewId();
            // squareLayout.SetBackgroundColor(Color.Blue);
            squareLayout.SetPadding(pad, pad, pad, pad);
            squareLayout.Clickable = true;
            squareLayout.Click += (s, e) =>
            {
                logger.Log("click android");
            };

            OfflineItemPage page = null;
            mountFrag(squareLayout, viewData, page = new OfflineItemPage(
                onPress: () =>
                {
                    var idx = (int) viewData.TryGet<object>("lastBindPos");
                    var vi = dataSource[idx];
                    if (SelectMode)
                    {
                        SetVideoSelectec(vi.vid, !IsVideoSelected(vi.vid));
                        page.Selected = IsVideoSelected(vi.vid);
                    }
                    else
                    {
                        MoviePlayView.OpenPlayView(dataSource[idx]);
                    }

                },
                onLongPress: () =>
                {
                    var idx = (int) viewData.TryGet<object>("lastBindPos");
                    var vi = dataSource[idx];
                    SetVideoSelectec(vi.vid, true);
                    SelectMode = true;
                },
                onCheckChanged: (b) => { }
            ));
            return squareLayout;
        }

        async void mountFrag(View cell, Dictionary<string, object> viewData, OfflineItemPage page)
        {
            while (myFragment.View.FindViewById(cell.Id) == null)
            {
                await Task.Delay(10);
                if (!myFragment.IsAdded)
                    return;
            }

            this.myFragment.ChildFragmentManager
                .BeginTransaction()
                .Replace(cell.Id, page.CreateSupportFragment(activity))
                .Commit();

            viewData["page"] = page;
            object p;
            if (viewData.TryGetValue("lastBindPos", out p))
                UpdateCell(cell, (int) p, viewData);
        }

        protected override void UpdateCell(View cell, int p, Dictionary<string, object> viewData)
        {
            var page = viewData.TryGet<OfflineItemPage>("page");
            if (page != null)
            {
                int idx = GetDataIndex(p);
                logger.Log("updatecell", p, idx);
                var vi = dataSource[idx];
                page.Update(dataSource[idx], offlineItemInfoList[p]);
                page.ShowCheckLayout = SelectMode;
                page.Selected = IsVideoSelected(vi.vid);
            }
        }

        bool IsVideoSelected(int vid) => selectedVideo.Contains(vid);
        void SetVideoSelectec(int vid, bool b)
        {
            if (b) selectedVideo.Add(vid);
            else selectedVideo.Remove(vid);

            selectOperatePage.Count = selectedVideo.Count;
        }

        void DeleteAll()
        {
            logger.Log("delete all");
        }

        void DeleteSelected()
        {
            logger.Log("delete selected");
            selectedVideo.ToList().ForEach(vid =>
            {
                GlobalImpl.VideoServer.DeleteVideoCache(vid);
            });
            SelectMode = false;
            ReloadData();
        }
    }
}